package filter.cookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

public class Cookie_code extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //确保输出编码不乱码
        req.setCharacterEncoding("gbk");
        resp.setCharacterEncoding("gbk");
        //创建写入对象
        PrintWriter out = resp.getWriter();
        //cookie,服务器端从客户端获取。
        Cookie[] cookies = req.getCookies();
        //判断cookie是否为空
        if(cookies!=null)
        {
            out.write("你上一次访问的时间：");
            for (int i = 0; i < cookies.length; i++) {
                //将每个cookie取出
                Cookie cookie = cookies[i];
                //判断cookie内容是否一致
                if (cookie.getName().equals("name")) {
                    String decode = URLDecoder.decode(cookie.getValue(), "utf-8");
                    System.out.println(decode);
                }
            }
        }else
        {
            out.write("这是你第一次访问本站。");
        }

        //用URLEncoder.encode设置编码保持不乱码。
        Cookie cookie=new Cookie("name", URLEncoder.encode("浩海","utf-8"));
        resp.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
